package com.telecom.sxint.app.api.controller.SystemController.App1MonthlyController;


import cn.zjtele.pubinfo.boot.redis.config.RedisHelper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.telecom.sxint.app.core.domain.entity.Systempojo.App1Monthlypojo.App1Assessment;
import com.telecom.sxint.app.core.domain.entity.Systempojo.App1Monthlypojo.App1MonthlyPerformanceScoresSummary;
import com.telecom.sxint.app.core.service.Systemservice.App1Monthlyservice.IApp1MonthlyPerformanceScoresSummaryService;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;
import cn.zjtele.pubinfo.common.http.response.ResponseData;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 
 * @since 2024-08-23
 */
@RestController
@Tag(name = "月度指标操作控制器", description = "月度指标操作管理")
@RequestMapping("/app1-system")
public class App1MonthlyPerformanceScoresSummaryController {
    @Autowired
    private IApp1MonthlyPerformanceScoresSummaryService performanceService;
    @Autowired
    private RedisHelper redisHelper;
    String cacheKey = "MonthlyPerformanceScoresSummary:Monthlist";


    @Operation(summary = "查询所有月度绩效评分信息")
    @GetMapping("/Monthlist")
    public ResponseData<List<App1MonthlyPerformanceScoresSummary>> listAll() {
        List<App1MonthlyPerformanceScoresSummary> cacheData = (List<App1MonthlyPerformanceScoresSummary>) redisHelper.valueGet(cacheKey);
        if (cacheData != null && !cacheData.isEmpty()) {
            return ResponseData.success(cacheData);
        }
        QueryWrapper<App1MonthlyPerformanceScoresSummary> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_delete", 0); // 只查询 is_delete 字段为 0 的记录
        List<App1MonthlyPerformanceScoresSummary> list = performanceService.list(queryWrapper);
        redisHelper.valueSet(cacheKey,list);
        return ResponseData.success(list);
    }

    @Operation(summary = "根据条件查询月度绩效评分信息")
    @PostMapping("/Monthsearch")
    public ResponseData<List<App1MonthlyPerformanceScoresSummary>> searchByConditions(@RequestBody App1MonthlyPerformanceScoresSummary filter) {
        QueryWrapper<App1MonthlyPerformanceScoresSummary> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_delete", 0)
                .like(StringUtils.isNotBlank(filter.getAbbreviation()), "abbreviation", filter.getAbbreviation())
                .like(StringUtils.isNotBlank(filter.getDepartmentName()), "department_name", filter.getDepartmentName());
        List<App1MonthlyPerformanceScoresSummary> results = performanceService.list(queryWrapper);
        return ResponseData.success(results);
    }

    @Operation(summary = "新增或更新月度绩效评分信息")
    @PostMapping("/Monthsave")
    public ResponseData saveOrUpdate(@RequestBody App1MonthlyPerformanceScoresSummary summary) {
        boolean result = performanceService.saveOrUpdate(summary);
        redisHelper.delete(cacheKey);
        return result ? ResponseData.success("保存成功") : ResponseData.success("保存失败");
    }

    @Operation(summary = "删除月度绩效评分信息")
    @DeleteMapping("/Monthdelete")
    public ResponseData deleteById(@RequestParam Integer id) {
        UpdateWrapper<App1MonthlyPerformanceScoresSummary> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("sequence_number", id) // 设置更新条件，这里假设id是更新条件
                .set("is_delete", 1); // 设置 is_delete 字段的值为 1
        performanceService.update(null, updateWrapper);
        redisHelper.delete(cacheKey);
        return ResponseData.success("删除成功");
    }

    @Transactional
    @Operation(summary = "计算总分和排名")
    @PostMapping("/Monthcalculate")
    public ResponseData calculateTotalAndRanking(@RequestBody(required = false) App1MonthlyPerformanceScoresSummary summary) {
        redisHelper.delete(cacheKey);
        // 如果请求数据为空，直接从数据库中计算总分和排名
        if (summary == null|| (summary.getPublicKpiScore() == null
                && summary.getFunctionalWorkScore() == null
                && summary.getGsScore() == null
                && summary.getPartyBranchIndex() == null
                && summary.getReverseSupportScore() == null)) {
            // 获取所有记录并计算总分
            QueryWrapper<App1MonthlyPerformanceScoresSummary> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("is_delete", 0); // 只查询 is_delete 字段为 0 的记录
            List<App1MonthlyPerformanceScoresSummary> allRecords = performanceService.list(queryWrapper);
            allRecords.forEach(record -> {
                BigDecimal recordPublicKpiScore = record.getPublicKpiScore() != null ? record.getPublicKpiScore() : BigDecimal.ZERO;
                BigDecimal recordFunctionalWorkScore = record.getFunctionalWorkScore() != null ? record.getFunctionalWorkScore() : BigDecimal.ZERO;
                BigDecimal recordGsScore = record.getGsScore() != null ? record.getGsScore() : BigDecimal.ZERO;
                BigDecimal recordPartyBranchIndex = record.getPartyBranchIndex() != null ? record.getPartyBranchIndex() : BigDecimal.ZERO;
                BigDecimal recordReverseSupportScore = record.getReverseSupportScore() != null ? record.getReverseSupportScore() : BigDecimal.ZERO;

                BigDecimal recordTotalScore = recordPublicKpiScore
                        .add(recordFunctionalWorkScore)
                        .add(recordGsScore)
                        .add(recordPartyBranchIndex)
                        .add(recordReverseSupportScore)
                        .setScale(2, RoundingMode.HALF_UP);  // 保留两位小数

                record.setTotalScore(recordTotalScore);
            });

            // 根据总分进行排序并确定排名
            List<App1MonthlyPerformanceScoresSummary> sortedRecords = allRecords.stream()
                    .sorted(Comparator.comparing(App1MonthlyPerformanceScoresSummary::getTotalScore).reversed())
                    .collect(Collectors.toList());

            for (int i = 0; i < sortedRecords.size(); i++) {
                App1MonthlyPerformanceScoresSummary record = sortedRecords.get(i);
                record.setRanking(i + 1);
                try {
                    performanceService.updateById(record);  // 更新数据库中的排名信息
                } catch (Exception e) {
                    // 处理更新异常
                    return ResponseData.failed("更新数据库失败", e.getMessage());
                }
            }

            return ResponseData.success("数据库中的记录已更新成功");
        } else {
            // 处理请求数据不为空的情况
            // 1. 计算总分
            BigDecimal publicKpiScore = summary.getPublicKpiScore() != null ? summary.getPublicKpiScore() : BigDecimal.ZERO;
            BigDecimal functionalWorkScore = summary.getFunctionalWorkScore() != null ? summary.getFunctionalWorkScore() : BigDecimal.ZERO;
            BigDecimal gsScore = summary.getGsScore() != null ? summary.getGsScore() : BigDecimal.ZERO;
            BigDecimal partyBranchIndex = summary.getPartyBranchIndex() != null ? summary.getPartyBranchIndex() : BigDecimal.ZERO;
            BigDecimal reverseSupportScore = summary.getReverseSupportScore() != null ? summary.getReverseSupportScore() : BigDecimal.ZERO;

            BigDecimal totalScore = publicKpiScore
                    .add(functionalWorkScore)
                    .add(gsScore)
                    .add(partyBranchIndex)
                    .add(reverseSupportScore)
                    .setScale(2, RoundingMode.HALF_UP);  // 保留两位小数

            // 验证总分是否超过100
            if (totalScore.compareTo(new BigDecimal("100")) > 0) {
                return ResponseData.failed("总分不能超过100", "输入错误");
            }

            summary.setTotalScore(totalScore);

            boolean isNewRecord = summary.getSequenceNumber() == null;

            if (isNewRecord) {
                // 2. 插入新记录并获取自动生成的 sequenceNumber
                try {
                    performanceService.save(summary);
                    // 在保存之后，重新加载记录以获取自动生成的 sequenceNumber
                    App1MonthlyPerformanceScoresSummary savedRecord = performanceService.getById(summary.getSequenceNumber());
                    summary.setSequenceNumber(savedRecord.getSequenceNumber());
                } catch (Exception e) {
                    // 处理插入失败的异常
                    return ResponseData.failed("插入失败", e.getMessage());
                }
            } else {
                // 更新已存在的记录
                try {
                    performanceService.updateById(summary);
                } catch (Exception e) {
                    // 处理更新失败的异常
                    return ResponseData.failed("更新失败", e.getMessage());
                }
            }
            QueryWrapper<App1MonthlyPerformanceScoresSummary> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("is_delete", 0); // 只查询 is_delete 字段为 0 的记录
            // 3. 获取所有记录并计算总分
            List<App1MonthlyPerformanceScoresSummary> allRecords = performanceService.list(queryWrapper);
            allRecords.forEach(record -> {
                BigDecimal recordPublicKpiScore = record.getPublicKpiScore() != null ? record.getPublicKpiScore() : BigDecimal.ZERO;
                BigDecimal recordFunctionalWorkScore = record.getFunctionalWorkScore() != null ? record.getFunctionalWorkScore() : BigDecimal.ZERO;
                BigDecimal recordGsScore = record.getGsScore() != null ? record.getGsScore() : BigDecimal.ZERO;
                BigDecimal recordPartyBranchIndex = record.getPartyBranchIndex() != null ? record.getPartyBranchIndex() : BigDecimal.ZERO;
                BigDecimal recordReverseSupportScore = record.getReverseSupportScore() != null ? record.getReverseSupportScore() : BigDecimal.ZERO;

                BigDecimal recordTotalScore = recordPublicKpiScore
                        .add(recordFunctionalWorkScore)
                        .add(recordGsScore)
                        .add(recordPartyBranchIndex)
                        .add(recordReverseSupportScore)
                        .setScale(2, RoundingMode.HALF_UP);  // 保留两位小数

                record.setTotalScore(recordTotalScore);
            });

            // 4. 根据总分进行排序并确定排名
            List<App1MonthlyPerformanceScoresSummary> sortedRecords = allRecords.stream()
                    .sorted(Comparator.comparing(App1MonthlyPerformanceScoresSummary::getTotalScore).reversed())
                    .collect(Collectors.toList());

            for (int i = 0; i < sortedRecords.size(); i++) {
                App1MonthlyPerformanceScoresSummary record = sortedRecords.get(i);
                record.setRanking(i + 1);
                try {
                    performanceService.updateById(record);  // 更新数据库中的排名信息
                } catch (Exception e) {
                    // 处理更新异常
                    return ResponseData.failed("更新数据库失败", e.getMessage());
                }
            }

            // 5. 获取并返回更新后的记录
            App1MonthlyPerformanceScoresSummary updatedSummary = performanceService.getById(summary.getSequenceNumber());
            //return updatedSummary != null ? ResponseData.success(updatedSummary) : ResponseData.failed("计算失败", "未找到更新记录");
            if (updatedSummary != null && updatedSummary.getIsDelete() == 0) {
                // 如果is_delete为0，返回成功响应
                return ResponseData.success(updatedSummary);
            } else {
                // 如果is_delete为1或对象为空，返回空结果或错误信息
                return ResponseData.failed("计算失败","未找到更新记录" );
            }
        }
    }
}
